package com.xl.exp.utils;

import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.Set;

@Component
public class RedisUtils {

    @Resource
    private JedisPool jedisPool;

    private Jedis getResource(){
        return jedisPool.getResource();
    }

    /**
     * 保存到redis中
     * @param key 序列化后的二进制key
     * @param value 序列化后的二进制value
     * @return 二进制value
     */
    public byte[] set(byte[] key, byte[] value) {
        Jedis jedis = getResource();
        try {
            jedis.set(key, value);
            return value;
        }finally {
            jedis.close();
        }
    }

    public void expire(byte[] key, int i) {

        Jedis jedis = getResource();
        try {
            jedis.expire(key, i);
        }finally {
            jedis.close();
        }
    }

    public byte[] get(byte[] key) {
        Jedis jedis = getResource();
        try {
            return jedis.get(key);
        }finally {
            jedis.close();
        }
    }

    public void del(byte[] key) {

        Jedis jedis = getResource();
        try {
            jedis.del(key);
        }finally {
            jedis.close();
        }
    }

    public Set<byte[]> keys(String key) {
        Jedis jedis = getResource();
        try {
            return jedis.keys((key + "*").getBytes());
        }finally {
            jedis.close();
        }
    }
}
